import { getSaltInfo, login, getInfo, loginout } from "@/api/current";
import crypto from "@/utils/crypto";

import { setUser, setUserToken, removeUser } from "@/store/modules/userStore";
import { setAppData, removeAppData } from "@/store/modules/appStore";
import { setRouter, removeRouter } from "@/store/modules/routerStore";

export const getInfoAction = () => {
  return async (dispatch) => {
    const { routers, menus, ...resProps } = await getInfo();
    dispatch(setRouter(routers));
    dispatch(setAppData(menus));
    dispatch(setUser(resProps));
  };
};
export const loginAction = (values) => {
  return async (dispatch) => {
    values.userName = values.userName.trim();
    const { salt, uuid } = await getSaltInfo();
    values.password = crypto.encrypt(values.password, salt);
    values.uuid = uuid;
    const token = await login(values);
    dispatch(setUserToken(token));
    dispatch(getInfoAction());
  };
};

export const logoutAction = () => {
  return async (dispatch) => {
    await loginout();
    dispatch(removeUser());
    dispatch(removeAppData());
    dispatch(removeRouter());
  };
};
